package cn.fl.institution.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.service.ICstNpBscInfoService;
import cn.fl.customer.vo.CstNpBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.institution.api.ISnbanksInsApiService;
import cn.fl.project.api.IPrjCstAccInfoApiService;
import cn.fl.project.condition.PrjCstAccInfoQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.service.IPrjBscExtService;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjCstAccInfoService;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjCstAccInfoVO;
import cn.fl.system.api.ISysInsIvkValApiService;
import cn.fl.system.dto.SysInsIvkValDTO;
import cn.fl.system.service.ISysRegionService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fl.inf.facade.api.ITransLogApi;
import fl.sn.facade.dto.CustomerBankInfoDTO;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @Description: 项目基础信息表 控制层  苏宁银行
 */
@Controller
@RequestMapping("/institution/snbanks")
public class PrjBscInfoInsSnbanksController {

	private static final Logger logger = LoggerFactory.getLogger(PrjBscInfoInsSnbanksController.class);

    @Autowired
    private IPrjBscInfoService prjBscInfoService; // 项目基础信息表

	@Autowired
	private IPrjCstAccInfoApiService prjCstAccInfoApiService; // 项目客户账户信息表

    @Autowired
    private ISysInsIvkValApiService sysInsIvkValApiService; // 资管机构承接调用结果
	
	@Autowired
	private ICstBscInfoService cstBscInfoService; // 客户基础信息
	
	@Autowired
	private ICstNpBscInfoService cstNpBscInfoService; // 自然人信息
	
	@Autowired
	private IPrjBscExtService prjBscExtService; //项目基础信息扩展表
	@Autowired
	private ISysRegionService sysRegionService;//查询省市县
	@Autowired
	private IPrjCstAccInfoService prjCstAccInfoService;//项目客户基础信息表
	@Autowired
	private ITransLogApi transLogApi;
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
    private ISnbanksInsApiService snbanksInsApiService;

    /**
     * 苏宁银行新增或修改项目客户账户信息及校验
     */
    @RequestMapping(value = "/snBanksAddOrModifyPrjAccInfo.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO snBanksAddOrModifyPrjAccInfo(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "snBanksAddOrModifyPrjAccInfo", "修改项目客户账户信息及校验"+ JSON.toJSONString(request.getParameterMap()), CurrentThreadContext.getCurrentUserName());
        String cstAccInfoId = request.getParameter("cstAccInfoId");//项目客户信息表id
        String insCode = request.getParameter("insCode");//机构code
        String prjId = request.getParameter("prjId");//项目id
        String cstId = request.getParameter("cstId");//客户id
        String cstNm = request.getParameter("cstNm");//客户姓名
        String bkNm = request.getParameter("bkNm");//银行名称
        String bkCd = request.getParameter("bkCd");//银行代码 -- 通用狮桥的数据字典表（CST0014） -- 资管特有的sys_cd_map_d表（M1041）
        String accNo = request.getParameter("accNo");//银行账号
        String mp = request.getParameter("mp");//手机号
        String certNo = request.getParameter("certNo");//身份证
        String certValidSDt = request.getParameter("certValidSDt");//身份证有效起始时间
        String certValidEDt = request.getParameter("certValidEDt");//身份证有效结束时间
        String lssueOffice = request.getParameter("lssueOffice");//签发机关
        String postProvince = request.getParameter("postProvince");//住宅省份
        String postCity = request.getParameter("postCity");//住宅城市
        String postAddr = request.getParameter("postAddr");//住宅地址明细
        DataResultVO dataResultVO = null;
        try {
            if (StringUtils.isEmpty(prjId)) {
                BaseLogUtils.info(logger, "snBanksAddOrModifyPrjAccInfo", "项目id为空.", CurrentThreadContext.getCurrentUserName());
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "项目信息不完整!");
            }
            if (StringUtils.isEmpty(cstId)) {
                BaseLogUtils.info(logger, "snBanksAddOrModifyPrjAccInfo", "客户id为空", CurrentThreadContext.getCurrentUserName());
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户信息不完整!");
            }
            if (StringUtils.isBlank(cstNm)) {
                BaseLogUtils.info(logger, "snBanksAddOrModifyPrjAccInfo", "客户名称为空", CurrentThreadContext.getCurrentUserName());
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户信息不完整!");
            }
            if(StringUtils.isBlank(bkNm) || StringUtils.isBlank(bkCd)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请选择开户银行信息!");
            }
            if(StringUtils.isBlank(accNo)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请填写银行卡号!");
            }
            if(StringUtils.isBlank(mp)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护银行预留手机号!");
            }
            if(StringUtils.isBlank(certValidSDt)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请输入证件有效起始日期!");
            }
            if(StringUtils.isBlank(certValidEDt)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请输入证件有效终止日期!");
            }
            if(StringUtils.isBlank(lssueOffice)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请输入身份证签发机关!");
            }
            if (StringUtils.isEmpty(postProvince)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护住宅地址省!");
            }
            if (StringUtils.isEmpty(postCity)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护住宅地址市!");
            }
            if (StringUtils.isEmpty(postAddr)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护住宅详细地址!");
            } else if (postAddr.length() > 150) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "住宅详细地址不能超过150个字符!");
            }
            PrjCstAccInfoQueryCondition prjCstAccInfoQC = new PrjCstAccInfoQueryCondition();
            prjCstAccInfoQC.setPrjId(Long.valueOf(prjId));
            prjCstAccInfoQC.setIsDel(BaseConstant.IS_YESNO_NO);
            prjCstAccInfoQC.setInsCode(PrjBscInfoConstant.PRJ_INS_CODE_SNBANKS);
            BaseLogUtils.info(logger, "snbanksGetPrjAccInfo", "根据prjId获取账户信息prjId"+prjId);
            List<PrjCstAccInfoVO> prjCstAccInfoVOS = this.prjCstAccInfoService.searchList(prjCstAccInfoQC);
            BaseLogUtils.info(logger, "snbanksGetPrjAccInfo", "根据cstID和insCode获取账户信息" + JSON.toJSONString(prjCstAccInfoVOS));
            PrjCstAccInfoQueryCondition condition = new PrjCstAccInfoQueryCondition();
            PrjCstAccInfoVO prjCstAccInfoVO = null;
            if (CollectionUtils.isNotEmpty(prjCstAccInfoVOS)) {
                prjCstAccInfoVO = prjCstAccInfoVOS.get(0);
                //开户结果 只定义了开户成功 和 开户中
                Map<String, String> resMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.SNBANKS_ACC_RES_CD);
                if (MapUtils.isEmpty(resMap)) {
                    BaseLogUtils.info(logger, "snBanksAddOrModifyPrjAccInfo", "开户结果字典未查询到");
                    return new DataResultVO(BaseConstant.IS_YESNO_NO, "开户结果字典未查询到!");
                }
                //开户成功 和 开户中 不可修改
                if (resMap.containsKey(prjCstAccInfoVO.getAccResCd())) {
                    BaseLogUtils.info(logger, "snBanksAddOrModifyPrjAccInfo", "苏宁银行"+resMap.get(prjCstAccInfoVO.getAccResCd())+"prjId:"+prjId);
                    return new DataResultVO(BaseConstant.IS_YESNO_NO, resMap.get(prjCstAccInfoVO.getAccResCd())+"不可修改信息!");
                }
                //说明该项目已存在账户信息 则跟据id进行修改
                condition.setId(prjCstAccInfoVO.getId());
            }

            condition.setPrjId(Long.valueOf(prjId));
            condition.setCstId(Long.valueOf(cstId));
            condition.setInsCode(insCode);
            condition.setCstNm(cstNm);
            condition.setAccNm(cstNm);
            condition.setBkCd(bkCd);
            condition.setBkNm(bkNm);
            condition.setAccNo(accNo);
            condition.setMp(mp);
            condition.setCertNo(certNo);
            condition.setCertTypCd(DictionaryConstant.CODE_CERT_TYP_CD_0);
            CstNpBscInfoVO cstNpBscInfoVO = new CstNpBscInfoVO();
            cstNpBscInfoVO.setId(Long.valueOf(cstId));
            cstNpBscInfoVO.setPostProvince(postProvince);
            cstNpBscInfoVO.setPostCity(postCity);
            cstNpBscInfoVO.setPostAddr(postAddr);
            cstNpBscInfoVO.setCertValidSDt(certValidSDt);
            cstNpBscInfoVO.setCertValidEDt(certValidEDt);
            cstNpBscInfoVO.setIssuingOrg(lssueOffice);
            this.cstNpBscInfoService.modify(cstNpBscInfoVO);
            dataResultVO = this.prjCstAccInfoService.modifyPrjAccInfo(condition);
            if(BaseConstant.IS_YESNO_YES == dataResultVO.getSuccess()){
                Map<String,String> resultMap = (Map<String, String>) dataResultVO.getData();
                String chkRstCd;
                String rstDesc;
                chkRstCd = resultMap.get("chkRstCd");
                rstDesc = resultMap.get("rstDesc");
                if(chkRstCd.equals("1")){
                    dataResultVO.setSuccess(BaseConstant.IS_YESNO_YES);
                    dataResultVO.setInfo("四要素信息校验通过");
                }else if(chkRstCd.equals("0") || chkRstCd.equals("2")){
                    dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                    dataResultVO.setInfo(rstDesc);
                }
            }
        } catch (BaseException ex) {
            dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            dataResultVO.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "snBanksAddOrModifyPrjAccInfo", "新增或修改项目客户账户信息及校验,prjId:" + prjId + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception e){
            BaseLogUtils.info(logger, "snBanksAddOrModifyPrjAccInfo", "保存失败，系统异常",CurrentThreadContext.getCurrentUserName()+e.getMessage(),e);
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "保存失败，系统异常");
        }
        BaseLogUtils.info(logger, "snBanksAddOrModifyPrjAccInfo", "新增或修改项目客户账户信息及校验返回=" + JSON.toJSONString(dataResultVO), CurrentThreadContext.getCurrentUserName());
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "snBanksAddOrModifyPrjAccInfo", "新增或修改项目客户账户信息及校验, PRJID:" + prjId, "-耗时:" + (endTm - startTm));
        return dataResultVO;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getVerificationCode.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object getVerificationCode(PrjCstAccInfoQueryCondition prjCstAccInfoQC,Long fundRasInsId,String typeCd) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "四要素校验通过");
        BaseLogUtils.info(logger, "getVerificationCode", "换卡保存获取验证码 项目客户账户信息Strat： prjCstAccInfoQC = " + JSONObject.toJSONString(prjCstAccInfoQC));
        /*PrjCstAccInfoVO prjCstAccInfo = this.prjCstAccInfoService.selectByPrjId(prjCstAccInfoQC.getPrjId());
        if(null != prjCstAccInfo && null != prjCstAccInfo.getId()){
            prjCstAccInfoQC.setId(prjCstAccInfo.getId());
        }*/
        PrjCstAccInfoQueryCondition prjCstAccInfo = new PrjCstAccInfoQueryCondition();
        prjCstAccInfo.setPrjId(prjCstAccInfoQC.getPrjId());
        prjCstAccInfo.setIsDel(BaseConstant.IS_YESNO_NO);
        prjCstAccInfo.setInsCode(PrjBscInfoConstant.PRJ_INS_CODE_SNBANKS);
        List<PrjCstAccInfoVO> prjCstAccInfoVOS = this.prjCstAccInfoService.searchList(prjCstAccInfo);
        if (CollectionUtils.isNotEmpty(prjCstAccInfoVOS)) {
            PrjCstAccInfoVO prjCstAccInfoVO = prjCstAccInfoVOS.get(0);
            prjCstAccInfoQC.setId(prjCstAccInfoVO.getId());
        }
        try{
            // 设置证件类型
            prjCstAccInfoQC.setCertTypCd("01");
            prjCstAccInfoQC.setInsCode(PrjBscInfoConstant.PRJ_INS_CODE_SNBANKS);
            // 四要素校验
            DataResultDTO resultDTO = this.prjCstAccInfoApiService.snVerifyModifyPrjAccInfo(prjCstAccInfoQC);
//            DataResultDTO resultDTO = this.prjCstAccInfoApiService.modifyPrjAccInfo(prjCstAccInfoQC);
            String chkRstCd = null, rstDesc = null;
            if(null != resultDTO && null != resultDTO.getData()){
                @SuppressWarnings("unchecked")
                Map<String, String> ckResMap = (Map<String, String>) resultDTO.getData();
                chkRstCd = ckResMap.get("chkRstCd");
                rstDesc = ckResMap.get("rstDesc");
                BaseLogUtils.info(logger, "getVerificationCode", "检验结果,chkRstCd=" + chkRstCd);
                //验证返回结果成功
                if("1".equals(chkRstCd)) {
                    // 3.15协议支付签约触发短信
                    BaseLogUtils.info(logger, "getVerificationCode", "调协议支付签约触发短信接口Start,传输信息：" +JSONObject.toJSONString(prjCstAccInfoQC));
                    // (custId, prjId, deviceId, terminal, ipAddress, macAddress, bankName, bankCardNum, phone)
                    String macAdr = prjCstAccInfoQC.getMacAdr();
                    if(StringUtils.isBlank(macAdr)){
                        macAdr = "1";
                    }
                    DataResultDTO dataResultDTO = this.snbanksInsApiService.signAgreementSMS(String.valueOf(prjCstAccInfoQC.getCstId()), String.valueOf(prjCstAccInfoQC.getPrjId()),
                            "31", "36", getRandomIp(), macAdr,
                            prjCstAccInfoQC.getBkCd(), prjCstAccInfoQC.getAccNo(), prjCstAccInfoQC.getMp(), false);
                    BaseLogUtils.info(logger, "getVerificationCode", "调协议支付签约触发短信接口End,传输信息：" +JSONObject.toJSONString(dataResultDTO));
                    if(dataResultDTO!=null){
                        if(BaseConstant.IS_YESNO_YES_NM.equals(dataResultDTO.getCode())){
                            result.setSuccess(BaseConstant.IS_YESNO_YES);
                            result.setInfo("验证码已发送承租人，请联系客户获取");
                        }else{
                            result.setSuccess(BaseConstant.IS_YESNO_NO);
                            result.setInfo(dataResultDTO.getInfo());
                        }
                    }else{
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo("验证码获取失败，请重新尝试；");
                    }
                } else {//验证失败
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("四要素信息校验未通过，请核查四要素"+"校验结果:"+rstDesc);
                }
            }else{
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("四要素信息校验异常");
            }
        }catch(BaseException ex){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "getVerificationCode", "获取验证码失败,prjId:" + prjCstAccInfoQC.getPrjId() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception e){
            BaseLogUtils.info(logger, "getVerificationCode", "获取验证码失败，系统异常",CurrentThreadContext.getCurrentUserName()+e.getMessage(),e);
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "获取验证码失败，系统异常");
        }
        return result;
    }

    //验证并换卡
    @SuppressWarnings("unused")
    @RequestMapping(value = "/exchangeCardSave.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object exchangeCardSave(PrjCstAccInfoQueryCondition prjCstAccInfoQC,Long fundRasInsId,String typeCd,String verificationCode) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "四要素校验通过");
        CustomerBankInfoDTO customerBankInfoDTO = new CustomerBankInfoDTO();
        BaseLogUtils.info(logger, "save", "换卡保存 项目客户账户信息Strat： prjCstAccInfoQC = " + JSONObject.toJSONString(prjCstAccInfoQC));
        /*PrjCstAccInfoVO prjCstAccInfo = this.prjCstAccInfoService.selectByPrjId(prjCstAccInfoQC.getPrjId());
        if(null != prjCstAccInfo && null != prjCstAccInfo.getId()){
            prjCstAccInfoQC.setId(prjCstAccInfo.getId());
        }*/
        PrjCstAccInfoQueryCondition prjCstAccInfo = new PrjCstAccInfoQueryCondition();
        prjCstAccInfo.setPrjId(prjCstAccInfoQC.getPrjId());
        prjCstAccInfo.setIsDel(BaseConstant.IS_YESNO_NO);
        prjCstAccInfo.setInsCode(PrjBscInfoConstant.PRJ_INS_CODE_SNBANKS);
        List<PrjCstAccInfoVO> prjCstAccInfoVOS = this.prjCstAccInfoService.searchList(prjCstAccInfo);
        PrjCstAccInfoVO prjCstAccInfoVO = new PrjCstAccInfoVO();
        if (CollectionUtils.isNotEmpty(prjCstAccInfoVOS)) {
            prjCstAccInfoVO = prjCstAccInfoVOS.get(0);
            prjCstAccInfoQC.setId(prjCstAccInfoVO.getId());
        }
        // 设置证件类型
        prjCstAccInfoQC.setCertTypCd("01");
        prjCstAccInfoQC.setInsCode(PrjBscInfoConstant.PRJ_INS_CODE_SNBANKS);
        try {
            //去验证四要素
            String certTypCd = null;
            String buOrgCd = null;
            // 四要素校验
            DataResultDTO resultDTO = this.prjCstAccInfoApiService.snVerifyModifyPrjAccInfo(prjCstAccInfoQC);
            String chkRstCd = null, rstDesc = null;
            if(null != resultDTO && null != resultDTO.getData()){
                @SuppressWarnings("unchecked")
                Map<String, String> ckResMap = (Map<String, String>) resultDTO.getData();
                chkRstCd = ckResMap.get("chkRstCd");
                rstDesc = ckResMap.get("rstDesc");
                BaseLogUtils.info(logger, "exchangeCardSave", "检验结果,chkRstCd=" + chkRstCd);
                //验证返回结果成功
                if("1".equals(chkRstCd)) {
                    BaseLogUtils.info(logger, "exchangeCardSave", "调换绑卡接口Strat： customerBankInfoDTO = " + JSONObject.toJSONString(prjCstAccInfoQC));
                    // (String prjId, String bankName, String bankCardNum, String phone, String phoneCode)
                    DataResultDTO dataResultDTO = this.snbanksInsApiService.accountSingBindChangeCard(String.valueOf(prjCstAccInfoQC.getPrjId()),
                            prjCstAccInfoQC.getBkCd(), prjCstAccInfoQC.getBkNm(), prjCstAccInfoQC.getAccNo(), prjCstAccInfoQC.getMp(), verificationCode);
                    BaseLogUtils.info(logger, "exchangeCardSave", "调换绑卡接口End： customerBankInfoDTO = " + JSONObject.toJSONString(dataResultDTO));
                    if(dataResultDTO!=null){
                        if(BaseConstant.IS_YESNO_YES_NM.equals(dataResultDTO.getCode())) {//换绑卡成功bankCard.getCode()
                            //保存换卡信息，先把之前存入的信息保存在 sys_ins_ivk_val（资管机构承接调用结果）  表 ,目的为了记录每一次换过的卡信息
                            SysInsIvkValDTO sysInsIvkValDTO = new SysInsIvkValDTO();
                            sysInsIvkValDTO.setPrjId(prjCstAccInfo.getPrjId());
                            sysInsIvkValDTO.setInsId(Long.valueOf(fundRasInsId));
                            sysInsIvkValDTO.setCstId(prjCstAccInfoVO.getCstId());
                            sysInsIvkValDTO.setTypeCd(typeCd);
                            sysInsIvkValDTO.setRespRule("mp:" + prjCstAccInfoVO.getMp() + ";" + "certNo:" + prjCstAccInfoVO.getCertNo() + ";" + "accNo:" + prjCstAccInfoVO.getAccNo() + ";" + "accNm:" + prjCstAccInfoVO.getAccNm() + ";" + "bkCd:" + prjCstAccInfoVO.getBkCd() + ";" + "bkNm:" + prjCstAccInfoVO.getBkNm() + ";" + "bkNo:" + prjCstAccInfoVO.getBkNo());
                            sysInsIvkValDTO.setCrtTm(new Date());
                            BaseLogUtils.info(logger, "exchangeCardSave", "换卡之前保存换卡记录Strat： sysInsIvkValDTO = " + JSONObject.toJSONString(sysInsIvkValDTO));
                            Long add = this.sysInsIvkValApiService.add(sysInsIvkValDTO);
                            BaseLogUtils.info(logger, "exchangeCardSave", "换卡之前保存换卡记录End： 保存sysInsIvkValDTO返回值 = " + JSONObject.toJSONString(add));
                            // Signing Agreement Num
                            if(dataResultDTO.getData()!=null){
                                prjCstAccInfoQC.setSignAgreementNo(String.valueOf(dataResultDTO.getData()));
                            }
                            //更新数据
                            DataResultDTO resultDTO1 = this.prjCstAccInfoApiService.modifyPrjAccInfo(prjCstAccInfoQC);
                            BaseLogUtils.info(logger, "exchangeCardSave", "换卡保存 项目客户账户信息End： prjCstAccInfoQC = " + JSONObject.toJSONString(prjCstAccInfoQC));
                            if (null != resultDTO1) {
                                @SuppressWarnings("unchecked")
                                Map<String, String> ckResMap1 = (Map<String, String>) resultDTO.getData();
                                chkRstCd = ckResMap1.get("chkRstCd");
                                rstDesc = ckResMap1.get("rstDesc");
                                if (chkRstCd.equals("1")) {//更新校验成功
                                    PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(Long.valueOf(prjCstAccInfo.getPrjId()));
                                    result.setSuccess(BaseConstant.IS_YESNO_YES);
                                    result.setInfo("修改成功，客户在+" + prjBscInfoVO.getFundRasInsNm() + "+还款银行卡已修改；");
                                } else {
                                    result.setSuccess(2);
                                    result.setInfo("四要素信息校验未通过，请核查四要素" + "更新数据后校验结果" + chkRstCd);
                                }
                            }
                        }else{//换绑卡失败
                            result.setSuccess(BaseConstant.IS_YESNO_NO);
                            result.setInfo(dataResultDTO.getInfo());
                        }
                    }else{//换绑卡失败
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo("换卡失败，请联系客户核实银行卡和预留手机号信息");
                    }
                }else if(chkRstCd.equals("0") || chkRstCd.equals("2")){//验证失败
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("四要素信息校验未通过，请核查四要素");
                }
            }else{
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("四要素信息校验异常");
            }
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.error(logger, "save", "换卡保存失败 " + ex.getMessage());
            ex.printStackTrace();
        }
        catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("保存失败!");
            BaseLogUtils.error(logger, "save", "换卡保存失败 " + ex.getMessage());
            ex.printStackTrace();
        }

        return result;
    }

    /**
     * 苏宁银行获取验证码
     */
    @RequestMapping(value = "/snbanksSendVcode.do", method = RequestMethod.GET)
    @ResponseBody
    public DataResultVO snbanksSendVcode(HttpServletRequest request) throws BaseException {
        BaseLogUtils.newLogger("苏宁银行获取验证码：" + JSON.toJSONString(request.getParameterMap()) + "，操作人：" + CurrentThreadContext.getCurrentUserName()).info();
        String prjCstAccId = request.getParameter("prjCstAccId");
        String prjId = request.getParameter("prjId");
        String cstId = request.getParameter("cstId");
        DataResultVO dataResultVO = new DataResultVO(BaseConstant.IS_YESNO_NO, "处理失败");
        if (StringUtils.isEmpty(prjId)) {
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "项目ID为空!");
        }
        if (StringUtils.isEmpty(prjCstAccId)) {
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "项目账户信息ID为空!");
        }
        if (StringUtils.isEmpty(cstId)) {
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户ID为空!");
        }
        try {
            DataResultDTO dto = this.snbanksInsApiService.signAgreementSMS(cstId, prjId, null, null, null, null, null, null, null, true);
//            BaseLogUtils.newLogger("苏宁银行获取验证码,prjId:" + prjId + "prjCstAccId" + prjCstAccId + ".dto:" + JSON.toJSONString(dto)).info();

            if (dto.getCode().equals(BaseConstant.IS_YESNO_YES_NM)) {
                dataResultVO.setSuccess(BaseConstant.IS_YESNO_YES);
            }
            if (dto.getCode().equals(BaseConstant.IS_YESNO_NO_NE)) {
                dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            }
            dataResultVO.setInfo(dto.getInfo());
//            dataResultVO.setData(dto.getData());
        } catch (BaseException ex) {
            dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            dataResultVO.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("苏宁银行获取验证码,prjId:" + prjId + "prjCstAccId" + prjCstAccId + ".ERROR:" + ex.getMessage()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception e) {
            BaseLogUtils.newLogger("苏宁银行获取验证码，系统异常,prjId:" + prjId + "prjCstAccId" + prjCstAccId + ".ERROR:" + e.getMessage()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "系统异常");
        }
        BaseLogUtils.newLogger("苏宁银行获取验证码返回dataResultVO=" + JSON.toJSONString(dataResultVO)).info();
        return dataResultVO;
    }

    /**
     * 苏宁银行开户
     */
    @RequestMapping(value = "/snbanksOpenAccount.do", method = RequestMethod.GET)
    @ResponseBody
    public DataResultVO snbanksOpenAccount(HttpServletRequest request) throws BaseException {
        BaseLogUtils.newLogger("苏宁银行开户：" + JSON.toJSONString(request.getParameterMap()) + "，操作人：" + CurrentThreadContext.getCurrentUserName()).info();
        String prjCstAccId = request.getParameter("prjCstAccId");
        String prjId = request.getParameter("prjId");
        String phoneCode = request.getParameter("phoneCode");
        DataResultVO dataResultVO = new DataResultVO(BaseConstant.IS_YESNO_NO, "处理失败");
        if (StringUtils.isEmpty(prjId)) {
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "项目ID为空!");
        }
        if (StringUtils.isEmpty(prjCstAccId)) {
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "项目账户信息ID为空!");
        }
        if (StringUtils.isEmpty(phoneCode)) {
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "验证码为空!");
        }
        try {
            DataResultDTO dto = this.snbanksInsApiService.openAccountAgain(prjId, phoneCode);

            dataResultVO.setSuccess(dto.getSuccess());
            dataResultVO.setInfo(dto.getInfo());
        } catch (BaseException ex) {
            dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            dataResultVO.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("苏宁银行开户,prjId:" + prjId + "prjCstAccId" + prjCstAccId + ".ERROR:" + ex.getMessage()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception e) {
            BaseLogUtils.newLogger("苏宁银行开户，系统异常,prjId:" + prjId + "prjCstAccId" + prjCstAccId  + ".ERROR:" + e.getMessage()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "系统异常");
        }
        BaseLogUtils.newLogger("苏宁银行开户返回dataResultVO=" + JSON.toJSONString(dataResultVO)).info();
        return dataResultVO;
    }

    /**
     * 获取随机IP
     *
     * @return
     */
    private static String getRandomIp() {
        // ip范围
        int[][] range = {{607649792, 608174079}, // 36.56.0.0-36.63.255.255
                {1038614528, 1039007743}, // 61.232.0.0-61.237.255.255
                {1783627776, 1784676351}, // 106.80.0.0-106.95.255.255
                {2035023872, 2035154943}, // 121.76.0.0-121.77.255.255
                {2078801920, 2079064063}, // 123.232.0.0-123.235.255.255
                {-1950089216, -1948778497}, // 139.196.0.0-139.215.255.255
                {-1425539072, -1425014785}, // 171.8.0.0-171.15.255.255
                {-1236271104, -1235419137}, // 182.80.0.0-182.92.255.255
                {-770113536, -768606209}, // 210.25.0.0-210.47.255.255
                {-569376768, -564133889}, // 222.16.0.0-222.95.255.255
        };
        Random rdint = new Random();
        int index = rdint.nextInt(10);
        String ip = num2ip(range[index][0] + new Random().nextInt(range[index][1] - range[index][0]));
        return ip;
    }
    /*
     * 将十进制转换成IP地址
     */
    private static String num2ip(int ip) {
        int[] b = new int[4];
        String x = "";
        b[0] = (int) ((ip >> 24) & 0xff);
        b[1] = (int) ((ip >> 16) & 0xff);
        b[2] = (int) ((ip >> 8) & 0xff);
        b[3] = (int) (ip & 0xff);
        x = Integer.toString(b[0]) + "." + Integer.toString(b[1]) + "." + Integer.toString(b[2]) + "." + Integer.toString(b[3]);

        return x;
    }
}
